<template>
  <div class="screen-container" :style="{ backgroundColor: bgColor }">
    <screenfull id="screenfull" class="screen-full hover-effect" @onScreenfull="handleScreenFull" />
    <el-button v-show="showMenu" class="fix-btn screen-btn" size="large" type="" @click="dialogRateVisible = true">设置汇率</el-button>
    <el-color-picker v-show="showMenu" v-model="bgColor" class="fix-btn color-btn" :predefine="predefineColors" />
    <div v-loading="listLoading" class="screen-box">
      <div class="screen-title">
        <h2>
          {{ name }}
          <!-- <img :src="h5Qr" alt=""> -->
        </h2>
        <div style="display: flex; justify-content: space-between">
          <div><span>共 {{ num[0] }} 件</span><span>已拍 {{ num[1] + num[2] }} 件</span><span>剩余 {{ num[3] }} 件</span></div>
          <span v-show="last">上一件 Lot {{ last.lot }} &nbsp; {{ last.state }} &nbsp; 最后出价：{{ toThousands(last.bid) }}</span>
          <span class="now-time">{{ dateFormat(date) }}</span>
        </div>
      </div>
      <div v-if="curr" class="screen-info">
        <div class="screen-info-left">
          <img class="goods-cover" :src="curr.cover" alt="">
        </div>
        <div class="screen-info-right">
          <h3 class="screen-info-right-name">
            Lot {{ curr.lot }}: {{ curr.name }}
            <h5 class="screen-info-right-spec">
              <span v-for="(item, index) in curr.spec" :key="index">{{ item.attr }} : {{ item.val }}</span>
            </h5>
          </h3>

          <div>
            <div class="goods-curr"><b> {{ toThousands(curr.curr) }}</b></div>
            <!-- <div class="goods-curr"><span class="label">RMB</span> {{ toThousands(rateVal.rmb ) || '未设置汇率' }}</div>
            <div class="goods-curr"><span class="label">HKD</span> {{ toThousands(rateVal.hkd ) || '未设置汇率' }}</div>
            <div class="goods-curr"><span class="label">USD</span> {{ toThousands(rateVal.usd ) || '未设置汇率' }}</div> -->
          </div>
          <div class="goods-curr-small">
            <div class="goods-curr-small-item"><span class="label">RMB</span> {{ toThousands(rateVal.rmb ) || '未设置汇率' }}</div>
            <div class="goods-curr-small-item"><span class="label">HKD</span> {{ toThousands(rateVal.hkd ) || '未设置汇率' }}</div>
            <div class="goods-curr-small-item"><span class="label">USD</span> {{ toThousands(rateVal.usd ) || '未设置汇率' }}</div>
          </div>
          <table class="goods-bids">
            <!-- <tr class="th">
              <td>竞拍者</td> <td>号牌</td> <td>出价</td>
            </tr> -->
            <tr v-if="bids.length === 0">
              <td colspan="3">-</td>
            </tr>
            <tr v-for="(item, index) in bids" :key="index">
              <td>{{ item.way }}</td> <td>{{ item.num }}</td> <td>{{ toThousands(item.bid) }}</td>
            </tr>
          </table>
        </div>
      </div>
      <div v-else class="goods-empty">
        <h3>暂无拍品，请稍后...</h3>
      </div>
    </div>
    <el-dialog title="请选择专场" :close-on-press-escape="false" :show-close="false" :close-on-click-modal="false" center :visible.sync="dialogTableVisible">
      <el-table
        v-loading="listLoading"
        :data="lotList"
        element-loading-text="Loading"
        height="350"
        @row-click="handleRowClick"
      >
        <el-table-column property="id" label="ID" width="100" />
        <el-table-column property="name" label="专场名称" show-overflow-tooltip max-width="400" />
      </el-table>
    </el-dialog>
    <el-dialog title="设置汇率" center :visible.sync="dialogRateVisible" @closed="handleRateClosed">
      <el-form :model="rate" label-position="left">
        <el-form-item label="RMB" label-width="50px">
          <el-input v-model="rate.rmb" :min="0" type="number" autocomplete="off" />
        </el-form-item>
        <el-form-item label="HKD" label-width="50px">
          <el-input v-model="rate.hkd" :min="0" type="number" autocomplete="off" />
        </el-form-item>
        <el-form-item label="USD" label-width="50px">
          <el-input v-model="rate.usd" :min="0" type="number" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRateVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSetRate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Screenfull from '@/components/Screenfull'
import { getScreenLots, getScreenData } from '@/api/ctrl'
import { toThousands } from '@/utils'

export default {
  components: { Screenfull },
  data () {
    return {
      lotId: '',
      listLoading: false,
      lotList: [],
      name: '',
      num: [0, 0, 0, 0],
      curr: {
        spec: []
      },
      last: false,
      bids: [],
      dialogTableVisible: false,
      dialogRateVisible: false,
      rate: {
        rmb: 0,
        hkd: '',
        usd: ''
      },
      h5Qr: '',
      showMenu: true,
      bgColor: '#333333',
      predefineColors: ['#333333', '#415E8F'],
      date: new Date()
    }
  },
  computed: {
    rateVal () {
      var data = {
        rmb: '',
        hkd: '',
        usd: ''
      }
      for (var key in this.rate) {
        if (this.rate[key]) {
          if (!isNaN(this.curr.curr)) {
            data[key] = Math.round(this.rate[key] * Number(this.curr.curr))
          } else {
            data[key] = this.curr.curr
          }
        }
      }
      return data
    }
  },
  watch: {
    $route () {
      const id = this.$route.query && this.$route.query.id
      if (!id) {
        this.fetchLots()
        this.dialogTableVisible = true
      } else {
        this.fetchData()
        this.wsSendMsg('join')
      }
    }
  },
  created () {
    const id = this.$route.query && this.$route.query.id
    this.lotId = id
    this.initWebSocket()
    const rateData = JSON.parse(window.localStorage.getItem('auc_ctrl_rate'))
    if (rateData) {
      this.rate = rateData
    }
    if (!id) {
      this.fetchLots()
    } else {
      this.fetchData()
    }
  },
  mounted () {
    document.addEventListener('visibilitychange', this.handleVisiable)
    this.timer = setInterval(() => {
      this.date = new Date()
    }, 1000)
  },
  beforeDestroy () {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  destroyed () {
    // this.wsSendMsg('leave')
  },
  methods: {
    handleVisiable (e) {
      if (e.target.visibilityState === 'visible') {
        if (!this.global.wsConnected) {
          this.initWebSocket()
        }
      }
    },
    fetchData () {
      this.listLoading = true
      getScreenData(this.lotId).then(res => {
        this.name = res.data.name
        this.num = res.data.num
        this.curr = res.data.curr
        this.last = res.data.last
        this.bids = res.data.bids
        this.h5Qr = res.data.h5Qr
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    fetchLots () {
      this.listLoading = true
      this.dialogTableVisible = true
      getScreenLots().then(res => {
        this.lotList = res.data
        this.total = res.data.total
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    handleRowClick (row) {
      this.lotId = row.id
      this.$router.push(`/screen?id=${row.id}`)
      this.dialogTableVisible = false
    },
    handleSetRate () {
      window.localStorage.setItem('auc_ctrl_rate', JSON.stringify(this.rate))
      this.dialogRateVisible = false
    },
    handleRateClosed () {
      const rateData = JSON.parse(window.localStorage.getItem('auc_ctrl_rate'))
      if (rateData) {
        this.rate = rateData
      } else {
        this.rate = {
          rmb: '',
          hkd: '',
          usd: ''
        }
      }
    },
    initWebSocket () {
      const wsData = {
        type: 'join',
        lot_id: this.lotId
      }
      if (this.global.ws) {
        if (this.global.wsConnected) {
          this.global.ws.send(JSON.stringify(wsData))
        }
      } else {
        this.global.ws = new WebSocket(process.env.VUE_APP_WS_HOST)
        this.global.setWs(this.global.ws)
      }
      this.global.ws.onopen = this.wsOnOpen
      this.global.ws.onerror = this.wsOnError
      this.global.ws.onmessage = this.wsOnMessage
      this.global.ws.onclose = this.wsOnClose
    },
    wsOnMessage (e) {
      var data = JSON.parse(e.data)
      // console.log(data)
      const arr = ['willHammer', 'faceLive', 'startAuc', 'cancelAuc', 'dealAuc', 'passAuc', 'reAuc', 'liveBid', 'netBid', 'phoneBid']
      if (Number(data.lot_id) === Number(this.lotId)) {
        switch (true) {
          // 进入、离开专场
          case data.type === 'join' || data.type === 'leave':
            console.log(`${data.uid} ${data.type} 专场 ${this.lotId}`)
            break
          case data.type === 'end':
            this.$alert('本专场已结束', {
              confirmButtonText: '关闭',
              callback: action => {
                this.$router.push(`/screen`)
              }
            })
            break
          case data.type === 'count':
            console.log('更新统计数据！')
            this.num = data.num
            break
          case arr.indexOf(data.type) > -1:
            if (data.goods || data.goods === false) {
              this.curr = data.goods
            }
            if (data.last || data.last === false) {
              this.last = data.last
            }
            if (data.type === 'startAuc' || data.type === 'reAuc') {
              this.bids = []
            }
            if (data.type === 'dealAuc') {
              this.$message({
                dangerouslyUseHTMLString: true,
                type: 'success',
                center: true,
                message: `<strong style="font-size: 2vw">${data.msg}</strong>`
              })
            }
            break
          // 出价更新出价列表 撤销出价
          case data.type === 'bid' || data.type === 'revoke':
            var { num, bid } = data
            var way = Number(num) === 0 ? '现场' : '网络'
            this.curr.curr = bid
            if (data.type === 'bid') {
              if (this.bids.length >= 3) {
                this.bids.pop()
              }
              this.bids.unshift({ num, bid, way })
            } else {
              this.bids.shift()
            }
            break
        }
      }
    },
    wsOnOpen () {
      console.log('组件内WebSocket连接成功!')
      this.global.wsConnected = true
      this.wsSendMsg('join')
    },
    wsOnError (e) {
      console.log('组件内WebSocket连接发生错误!')
      this.global.wsConnected = false
    },
    wsOnClose () {
      console.log('组件内WebSocket连接关闭!')
      this.global.wsConnected = false
      this.global.ws = new WebSocket(process.env.VUE_APP_WS_HOST)
      this.global.setWs(this.ws)
    },
    wsSendMsg (type) {
      if (this.global.ws && this.global.wsConnected) {
        var msg = {
          type,
          lot_id: this.lotId
        }
        this.global.ws.send(JSON.stringify(msg))
      }
    },
    toThousands,
    handleScreenFull (val) {
      this.showMenu = val
    },
    dateFormat (time) {
      var date = new Date(time)
      var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      // 拼接
      return hours + ':' + minutes + ':' + seconds
    }
  }
}
</script>

<style lang="scss" scoped>
.screen-container {
  height: 100vh;
  background: #333;
  color: #fff;
  // overflow: hidden;
  .el-table:hover {
    cursor: pointer;
  }
  .fix-btn {
    position: fixed;
    top: 20px;
    right: 20px;
    font-size: 1.4vw;
    padding: 15px 25px;
    &.screen-btn {
      right: calc(70px + 1.4vw);
    }
  }
  .screen-title {
    text-align: center;
    padding: 40px 15px 20px ;
    font-size: 2vw;
    h2 {
      margin-top: 0;
      margin-bottom: 15px;
      position: relative;
      margin-left: calc(30px - 2.5vw);
      img {
        width: 5vw;
        height: 5vw;
        position: absolute;
        top: -1.5vw;
        margin-left: 30px;
        border: 4px solid #fff;
      }
    }
    span {
      font-size: 1.8vw;
      margin-right: 10px;
      &.now-time {
        font-weight: bold;
        color: rgb(255, 186, 89);
      }
    }
  }
  .screen-full {
    position: fixed;
    top: 20px;
    left: 20px;
    display: inline-block;
    font-size: 1.6vw;
    color: #fff;
    &.hover-effect {
      cursor: pointer;
      transition: background .3s;
      &:hover {
        background: rgba(0, 0, 0, .025)
      }
    }
  }
  .screen-info {
    display: flex;
    // align-items: center;
    height: calc(100vh - 75px - 2.5vw - 1.5em);
    padding: 0;
    font-size: 2vw;
    box-sizing: border-box;
    background: #0057f8;
    &-left {
      width: 40vw;
      background: #F8FFFF;
      display: flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;
      .goods-cover {
        max-width: 100%;
        max-height: calc(100vh - 75px - 2.5vw - 1.5em);
      }
    }
    &-right {
      // width: 40vw;
      flex: 1;
      height: 100%;
      background: rgb(0, 87, 248);
      padding: 1.5vw 25px;
      display: flex;
      justify-content: space-between;
      flex-direction: column;
      &-name{
        font-size: 2.6vw;
        margin: 10px 0 0;
        text-align: center;
        font-weight: 600;
        border-bottom: 1px solid #fff;
        padding-bottom: 0.8vw;
      }
      &-spec {
        font-size: 1.8vw;
        margin: 15px 0 12px;
        font-weight:normal;
      }
      // h4 {
      //   font-size: 2.2vw;
      //   overflow: hidden;
      //   text-overflow:ellipsis;
      //   white-space: nowrap;
      //   font-family: "Baskerville10Pro", Georgia, Cambria, "Times New Roman", Times, serif;
      // }
      .goods-curr {
        font-size: 2.8vw;
        line-height: 1.25;
        text-align: center;
        display: flex;
        justify-content: space-around;
        padding: 0 15%;
        // 只保留jpy时的大小
        font-size: 6vw;
        &-small {
          display: flex;
          margin: 10px auto;
          font-size: 3.2vw;
          &-item {
            display: flex;
            align-items: center;
            padding: 10px 20px;
            flex-direction: column;
            border: 1px solid #fff;
            .label {
              font-weight: 600;
              margin-bottom: 10px;
            }
          }
        }
      }
      .label {
        display: inline-block;
      }
      .goods-bids {
        width: 100%;
        text-align: center;
        border-collapse: collapse;
        line-height: 1.5;
        font-size: 2.5vw;
        border-top: 1px solid #fff;
        tr {
          &:first-of-type {
            td {
              padding-top: 1.3vw;
              padding-bottom: 5px;
            }
          }
          td {
            width: 33%;
          }
        }
      }
      @media screen and (max-width: 1500px) {
        h3 {
          font-size: 2.6vw;
        }
        h4 {
          font-size: 2vw;
        }
        .goods-curr {
          font-size: 2.2vw;
          line-height: 1.5;
          padding: 0 20%;
          // 只保留jpy时的大小
          font-size: 2.6vw;
          &-small {
            font-size: 1.95vw;
          }
        }
        .goods-bids {
          font-size: 1.9vw;
          line-height: 1.4;
        }
      }
    }
  }
  .goods-empty {
    color: burlywood;
    text-align: center;
    font-size: 2.1vw;
    line-height: calc(100vh - 100px - 20vw);
  }
}
</style>
<style lang="scss">
.fix-btn {
  .el-color-picker__trigger {
    background: #fff !important;
    width: calc(32px + 1.4vw);
    height: calc(32px + 1.4vw);
    position: fixed;
    top: 20px;
    right: 20px;
  }
}
</style>
